package com.cg.controller;

import com.cg.common.BaseContext;
import com.cg.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 职位收藏
 */
@Slf4j
@RestController
@RequestMapping("/job")
public class JobFavoriteController {

    private static final String JOB_FAVORITED_SET_KEY = "job:favorited:";       // Set(userId)
    private static final String JOB_FAVORITE_COUNT_KEY = "job:favoriteCount:";  // String(count)

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private com.cg.mapper.JobFavoriteMapper jobFavoriteMapper;

    /**
     * 查询职位收藏信息：总数 + 当前用户是否已收藏
     */
    @GetMapping("/favorites/{id}")
    public Result<Map<String, Object>> queryJobFavorites(@PathVariable("id") Long jobId,
                                                         @RequestParam(value = "type", required = false) String type) {
        log.info("[JOB FAVORITE] query favorites, jobId={}, type={}, userId={}", jobId, type, BaseContext.getCurrentId());
        String setKey = JOB_FAVORITED_SET_KEY + jobId;
        String cntKey = JOB_FAVORITE_COUNT_KEY + jobId;

        Long currentUserId = BaseContext.getCurrentId();
        boolean favoritedByMe = false;
        if (currentUserId != null) {
            Boolean isMember = stringRedisTemplate.opsForSet().isMember(setKey, currentUserId.toString());
            favoritedByMe = Boolean.TRUE.equals(isMember);
        }

        String val = stringRedisTemplate.opsForValue().get(cntKey);
        long total = 0L;
        try { total = val == null ? 0L : Long.parseLong(val); } catch (Exception ignored) { }
        if (total == 0L && type != null && !type.isEmpty()) {
            try { total = jobFavoriteMapper.count(mapType(type), jobId.intValue()); } catch (Exception ignored) { }
        }

        Map<String, Object> resp = new HashMap<>();
        resp.put("favorited", total);
        resp.put("isFavorite", favoritedByMe);
        return Result.success(resp);
    }

    /**
     * 收藏/取消收藏（幂等切换）
     */
    @PutMapping("/favorite/{id}")
    public Result<String> favoriteJob(@PathVariable("id") Long jobId,
                                      @RequestParam(value = "type", required = false) String type) {
        Long userId = BaseContext.getCurrentId();
        log.info("[JOB FAVORITE] toggle favorite, jobId={}, type={}, userId={}", jobId, type, userId);
        if (userId == null) {
            log.warn("[JOB FAVORITE] user not login, abort");
            return Result.error("未登录，无法收藏");
        }

        String setKey = JOB_FAVORITED_SET_KEY + jobId;
        String cntKey = JOB_FAVORITE_COUNT_KEY + jobId;

        Boolean isMember = stringRedisTemplate.opsForSet().isMember(setKey, userId.toString());
        if (Boolean.FALSE.equals(isMember)) {
            Long added = stringRedisTemplate.opsForSet().add(setKey, userId.toString());
            stringRedisTemplate.opsForValue().increment(cntKey);
            log.info("[JOB FAVORITE] favorited in redis, added={}, jobId={}", added, jobId);
            if (type != null && !type.isEmpty()) {
                try { jobFavoriteMapper.favorite(mapType(type), jobId.intValue(), userId); } catch (Exception ignored) { }
            }
            return Result.success("favorited");
        } else {
            Long removed = stringRedisTemplate.opsForSet().remove(setKey, userId.toString());
            stringRedisTemplate.opsForValue().decrement(cntKey);
            log.info("[JOB FAVORITE] unfavorited in redis, removed={}, jobId={}", removed, jobId);
            if (type != null && !type.isEmpty()) {
                try { jobFavoriteMapper.unfavorite(mapType(type), jobId.intValue(), userId); } catch (Exception ignored) { }
            }
            return Result.success("unfavorited");
        }
    }

    private String mapType(String type){
        switch (type == null ? "" : type.toLowerCase()){
            case "java": return "crawler_py_java";
            case "back": return "crawler_py_back";
            case "c": return "crawler_py_c";
            case "front": return "crawler_py_front";
            case "go": return "crawler_py_go";
            case "javascript": return "crawler_py_javascript";
            case "nodejs": return "crawler_py_nodejs";
            case "operations": return "crawler_py_operations";
            case "python": return "crawler_py_python";
            case "test": return "crawler_py_test";
            case "web": return "crawler_py_web";
            default: return "crawler_py_java";
        }
    }
}


